<!--
 * @Author: your name
 * @Date: 2021-04-06 15:51:24
 * @LastEditTime: 2021-04-07 08:57:38
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /Interview Files/大纲/1114图片懒加载.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片懒加载</title>
</head>

<body>
    <p>原理:</p>
    <p>
        offsetTop - scroolTop &lt; clientHeight<br/> 元素到顶部的距离 - 屏幕滚动距离 &lt; 屏幕高度
    </p>
    <div>
        <img data-src="./images/1.jpg" alt="">
        <img data-src="./images/2.jpg" alt="">
        <img data-src="./images/3.jpg" alt="">
        <img data-src="./images/4.jpg" alt="">
        <img data-src="./images/5.jpg" alt="">
        <img data-src="./images/6.jpg" alt="">
        <img data-src="./images/7.jpg" alt="">
        <img data-src="./images/8.jpg" alt="">
        <img data-src="./images/9.jpg" alt="">
        <img data-src="./images/10.jpg" alt="">
        <img data-src="./images/1.jpg" alt="">
        <img data-src="./images/2.jpg" alt="">
    </div>
</body>

</html>
<script>
    var imgs = document.querySelectorAll('img');

    //offsetTop是元素与offsetParent的距离，循环获取直到页面顶部
    function getTop(e) {
        var T = e.offsetTop;
        while (e = e.offsetParent) {
            T += e.offsetTop;
        }
        return T;
    }

    function lazyLoad(imgs) {
        var H = document.documentElement.clientHeight; //获取可视区域高度
        var S = document.documentElement.scrollTop || document.body.scrollTop;
        for (var i = 0; i < imgs.length; i++) {
            if (H + S > getTop(imgs[i])) {
                imgs[i].src = imgs[i].getAttribute('data-src');
            }
        }
    }

    window.onload = window.onscroll = function() { //onscroll()在滚动条滚动的时候触发
        lazyLoad(imgs);
    }
</script>